package indexer;

import japa.parser.JavaParser;
import japa.parser.ParseException;
import japa.parser.ast.CompilationUnit;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Stack;
import java.util.logging.Logger;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexDeletionPolicy;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.NoDeletionPolicy;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.freelunch.visitors.MethodVisitor;

public class MethodIndexer {

	public static void main(String[] args) {
		recDir("C:\\HOUSE\\E11.19\\eBBS_AccountTerminalMap/ejbModule/scb/ebbs/ecodes\\");
	}

	private static final int BUCKET_VOLUME = 100;
	private static final Logger log = Logger.getLogger(MethodIndexer.class.toString());
	public static void recDir(String args) {
		Directory fdr;
		try {
			String index_store = System.getProperty("index");
			fdr = FSDirectory.open(new File(index_store));
			Analyzer standardAnalyzer = new StandardAnalyzer(Version.LUCENE_35);

			IndexDeletionPolicy deletionPolicy = NoDeletionPolicy.INSTANCE;

			IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_35, standardAnalyzer);
			indexWriterConfig.setIndexDeletionPolicy(deletionPolicy);
			IndexWriter indexWriter = new IndexWriter(fdr, indexWriterConfig);

			Stack<File> stk = new Stack<File>();
			File files = new File(args);
			stk.push(files);
			int lng = 0;

			while (!stk.isEmpty()) {
				File file = stk.pop();
				if (file.isDirectory()) {
					for (File fl : file.listFiles()) {
						if (fl.isDirectory()) {
							stk.push(fl);
						}
						if (!fl.getName().endsWith(".java")) {
							continue;
						}
						log.info(fl.toString());
						
						lng = (lng + 1) % BUCKET_VOLUME;

						CompilationUnit cu;
						InputStream in = new FileInputStream(fl);
						try {
							cu = JavaParser.parse(in);
							new MethodVisitor().visit(cu, indexWriter,
									fl.getAbsolutePath());
						} catch (ParseException e) {

							e.printStackTrace();
						} finally {
							if (in != null)
								in.close();
						}
					}
				}
			}
			indexWriter.commit();
			if (indexWriter != null)
				indexWriter.close();
		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}
	}
}
